<?php

namespace App\Libs\Strategy;


use Illuminate\Database\Eloquent\Model;

class DisplayData implements IStrategy
{
    //数据模型
    private $model;

    //分页数量 是否分页
    private $page;

    //排序规格
    private $latest = 'created_at';

    //回调
    protected $callback;

    //预加载
    protected $with = [];

    protected $query = null;

    protected $first = false;

    public function __construct($page,$callback,Model $model)
    {
        $this->model = $model;
        $this->page = $page;
        $this->callback = $callback;
    }

    public function algorithm()
    {
        return $this->page === 0 ?  $this->getAll() : $this->paginate();
    }


    private function getAll(){
       $model = $this->model->where(function ($query){
            if(is_callable($this->callback))
            {
                $this->query = call_user_func($this->callback,$query,$this);
            }
       });
       $seach = $this->first === false ? 'get' : 'first';
       return is_null($this->query) ? $model->latest($this->latest)->{$seach}():$this->query->latest($this->latest)->{$seach}();
    }


    private function paginate(){
        $model =  $this->model->where(function ($query){
            if(is_callable($this->callback))
            {
               $this->query = call_user_func($this->callback,$query,$this);
            }
        });
        return is_null($this->query)? $model->latest($this->latest)->paginate($this->page):$this->query->latest($this->latest)->paginate($this->page);
    }


    public function setFirst($first = false)
    {
        $this->first = $first;
    }

    public function setLatest($latest)
    {
        $this->latest = $latest;
    }
}
